package com.andatsoft.laisim.activity.setting;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.TextView;

import com.andatsoft.laisim.R;
import com.andatsoft.laisim.activity.BaseActivity;
import com.andatsoft.laisim.utils.ToastMessage;

/**
 * @author Paul
 * 
 */
public class NewFeatureActivity extends BaseActivity {

	private final String NEW_FEATURE_HOST = "http://lucky-sphinx-614.appspot.com/laisimgae";
	private EditText mEtName;
	private EditText mEtEmail;
	private EditText mEtContent;
	private TextView mTvSend;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setting_new_feature);
		initViews();
		setupListeners();
	}

	private void initViews() {
		mEtName = (EditText) findViewById(R.id.et_new_feature_name);
		mEtEmail = (EditText) findViewById(R.id.et_new_feature_email);
		mEtContent = (EditText) findViewById(R.id.et_new_feature_content);

		mTvSend = (TextView) findViewById(R.id.tv_new_feature_send);
		if (mTvSend != null) {
			mTvSend.setTextColor(getSelectedTheme().getNormalTextColor());
		}
	}

	private void setupListeners() {
		if (mTvSend != null) {
			mTvSend.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						setAlpha(v, 0.5f);
						break;
					case MotionEvent.ACTION_UP:
						setAlpha(v, 1.0f);
						String name = mEtName.getText().toString();
						String email = mEtEmail.getText().toString();
						String content = mEtContent.getText().toString();
						if (isInfoValid(name, email, content)) {
							new SendDataTask(name, email, content).execute();
						} else {
							// invalid info
							new ToastMessage(getApplicationContext())
									.showLongMessage(getString(R.string.toast_new_feature_invalid));
						}

						break;
					case MotionEvent.ACTION_CANCEL:
						setAlpha(v, 1.0f);
						break;

					default:
						break;
					}
					return true;
				}
			});
		}
	}

	private boolean isInfoValid(String name, String email, String content) {

		if (name == null || name.equals(""))
			return false;

		if (email == null || email.equals("") || email.length() < 5)
			return false;

		if (content == null || content.equals("") || content.length() < 5)
			return false;
		return true;
	}

	private int sendPostData(String name, String email, String content) {

		// ///////////////////
		HttpParams httpParameters = new BasicHttpParams();
		// Set the timeout in milliseconds until a connection is established.
		// The default value is zero, that means the timeout is not used.
		int timeoutConnection = 2000;
		HttpConnectionParams.setConnectionTimeout(httpParameters,
				timeoutConnection);
		// Set the default socket timeout (SO_TIMEOUT)
		// in milliseconds which is the timeout for waiting for data.
		int timeoutSocket = 5000;
		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
		HttpClient httpClient = new DefaultHttpClient(httpParameters);
		HttpPost httpPost = new HttpPost(NEW_FEATURE_HOST);
		try {
			List<NameValuePair> data = new ArrayList<NameValuePair>();
			data.add(new BasicNameValuePair("username", name));
			data.add(new BasicNameValuePair("email_address", email));
			data.add(new BasicNameValuePair("content", content));

			httpPost.setEntity(new UrlEncodedFormEntity(data, "UTF-8"));

			// execute
			HttpResponse response = httpClient.execute(httpPost);
			if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
				return 0;
			return 1;
		} catch (ClientProtocolException e) {
			return 0;
		} catch (IOException e) {
			return 0;
		}
	}

	class SendDataTask extends AsyncTask<Void, Void, Integer> {

		private String name;
		private String email;
		private String content;

		public SendDataTask(String name, String email, String content) {
			this.name = name;
			this.email = email;
			this.content = content;
		}

		@Override
		protected void onPreExecute() {
			new ToastMessage(getApplicationContext())
					.showShortMessage(getString(R.string.toast_new_feature_sending));
			mTvSend.setEnabled(false);
		}

		@Override
		protected Integer doInBackground(Void... params) {
			return sendPostData(name, email, content);
		}

		@Override
		protected void onPostExecute(Integer result) {
			int re = result;
			if (re == 0) {
				// connection error
				new ToastMessage(getApplicationContext())
						.showLongMessage(getString(R.string.toast_new_feature_connection_error));
			} else {
				// ok
				new ToastMessage(getApplicationContext())
						.showLongMessage(getString(R.string.toast_new_feature_thanks));
			}
			mTvSend.setEnabled(true);
		}

	}
}
